<template>
  <div>
    <navs :isDark="true"></navs>
    <div class="cont">
      <img src="../assets/image/home/home2.png" class="home2" alt="" />
      <div class="flex-ct hcbox">
        <div class="hc">{{ $t("home.synthesis") }}</div>
        <div class="flex-en">
          <div>{{ $t("home.accountBalance") }}</div>
          <img src="../assets/image/other/svg.png" class="svg" alt="" />
          <div v-if="tokenType == 1">{{ aimeBalance }} AIME</div>
          <div v-if="tokenType == 2">{{ risBalance }} RIS</div>
          <div v-if="tokenType == 3">{{ SGDHBalance }} SGDH</div>
          <div v-if="tokenType == 4">{{ RiseBalance }} RISE-LP</div>
          <div v-if="tokenType == 5">{{ WKBalance }} WK</div>
        </div>
      </div>
      <div class="Balance">
        <div class="flex-ct">
          <div>{{ $t("home.nftBalance") }} {{ nftBalance }}</div>
          <div class="MAX">{{ $t("home.max") }}</div>
        </div>
        <div class="flex-ct tokenTypebox">
          <div>{{ $t("home.synthesisToken") }}</div>
          <div class="selector" @click="showTokenPicker = true">
            <span class="selected-text">{{ tokenTypeLabel }}</span>
            <van-icon name="arrow-down" class="arrow-icon" />
          </div>
          <!-- <select v-model="tokenType">
            <option :value="2">RIS</option>
            <option :value="1">RISE-LP</option>
          </select> -->
        </div>
        <input type="number" disabled v-model="numbers" class="input" min="1" />
        <div class="flex-ct RISbox">
          <div class="flex-st">
            <img src="../assets/image/other/svg2.png" class="svg2" alt="" />
            <div>
              <!-- 带参数的动态文本 -->
              {{
                $t("home.synthesisNeedTokenUsdt", {
                  token:
                    tokenType === 1
                      ? "AIME"
                      : tokenType === 2
                      ? "RIS"
                      : tokenType === 3
                      ? "SGDH"
                      : tokenType === 4
                      ? "RISE-LP"
                      : "WK",
                })
              }}
            </div>
          </div>
          <div v-if="tokenType === 1">
            {{ needAimenum || 0 }}
          </div>
          <div v-else-if="tokenType === 5">
            {{ needUsdt * 5 || 0 }}
          </div>
          <div v-else>
            {{
              ((tokenType === 2 ? needRis : needUsdt) * numbers).toFixed(2) || 0
            }}
          </div>
        </div>

        <div class="flex-ct RISbox">
          <div class="flex-st">
            <img src="../assets/image/other/svg2.png" class="svg2" alt="" />
            <div>{{ $t("home.synthesisNeedUsdt") }}</div>
          </div>
          <div>{{ needUsdt * numbers }}</div>
        </div>
        <button class="hcbtn" @click="mergeNFT" :disabled="isMerging">
          {{
            isMerging ? $t("home.synthesisInProgress") : $t("home.synthesis")
          }}
        </button>
      </div>
      <div class="helistbox">
        <div class="title">{{ $t("home.synthesisRecord") }}</div>
        <div class="helistlist">
          <div class="flex-cc header">
            <div>{{ $t("home.nftId") }}</div>
            <div>{{ $t("home.synthesisTime") }}</div>
          </div>
          <div v-for="(item, i) in mergeRecords" :key="i" class="record-item">
            <div class="flex-cc">
              <div class="num">#{{ item.tokenId }}</div>
              <div>{{ formatTime(item.mergeTs) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <foot></foot>
    <van-popup v-model:show="showTokenPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="tokenOptions"
        :confirm-button-text="$t('common.confirm')"
        :cancel-button-text="$t('common.cancel')"
        @confirm="onTokenConfirm"
        @cancel="showTokenPicker = false"
      />
    </van-popup>
  </div>
</template>
<script>
import navs from "../components/nav.vue";
import foot from "./components/foot.vue";
import {
  web3,
  AIMEMainContract,
  RISContract,
  USDTContract,
  AIMEContract,
  RUSELPContract,
  SGDHContract,
  WKContract,
  AIMENFTContract,
} from "@/assets/js/web3.js";
import { Toast } from "vant";

export default {
  components: { navs, foot },
  data() {
    return {
      numbers: 1,
      tokenType: 1, // 2: RIS, 1: AIME
      showTokenPicker: false,
      tokenOptions: [
        { text: "AIME", value: 1 },
        { text: "RIS", value: 2 },
        { text: "RISE-LP", value: 4 },
        { text: "SGDH", value: 3 },
        { text: "WK", value: 5 },
      ],
      mergeRecords: [],
      risBalance: 0,
      aimeBalance: 0,
      nftBalance: 0,
      needRis: 0,
      needAime: 0,
      needUsdt: 0,
      risPrice: 0.25,
      nft1Reward: 0,
      isMerging: false,
      currentAccount: "",
      RiseBalance: 0,
      leaderAddress: "",
      SGDHBalance: 0,
      WKBalance: 0,
      needAimenum: 0,
    };
  },
  computed: {
    tokenTypeLabel() {
      const opt = this.tokenOptions.find(
        (item) => item.value === this.tokenType
      );
      return opt ? opt.text : "";
    },
  },
  // computed: {
  //   currentAccount() {
  //     return sessionStorage.getItem("account") || "";
  //   },
  //   leaderAddress() {
  //     return sessionStorage.getItem("leaderAddress") || "";
  //   },
  // },
  mounted() {
    this.currentAccount = sessionStorage.getItem("account") || "";
    this.leaderAddress = sessionStorage.getItem("leaderAddress") || "";
    console.log(this.currentAccount);
    console.log(this.leaderAddress);
    this.loadData();
    this.getAccountData();
    this.calculateDynamicTokenNeed();
  },
  methods: {
    async calculateDynamicTokenNeed() {
      try {
        if (this.tokenType == 1) {
          const res = await AIMEMainContract.methods.nft1MergePrice().call();
          const baseUsdt = Number(web3.utils.fromWei(res, "ether"));

          const nftCount = await AIMENFTContract.methods
            .nftTypeCounter(1)
            .call();
          this.needAimenum = ((baseUsdt * 2000) / nftCount).toFixed(2);
        }
      } catch (err) {
        console.error("动态计算失败:", err);
      }
    },
    onTokenConfirm(value) {
      this.tokenType = value.value;
      this.showTokenPicker = false;
      this.calculateDynamicTokenNeed();
    },
    async getAccountData() {
      if (!this.currentAccount) return;
      try {
        const res = await AIMEMainContract.methods
          .queryUserAccountData(this.currentAccount)
          .call();
        console.log(res);
        const tetRiseBalance = await RUSELPContract.methods
          .balanceOf(this.currentAccount)
          .call();
        this.RiseBalance = Number(
          web3.utils.fromWei(tetRiseBalance, "ether")
        ).toFixed(2);
        const SGDHBalance = await SGDHContract.methods
          .balanceOf(this.currentAccount)
          .call();
        this.SGDHBalance = Number(
          web3.utils.fromWei(SGDHBalance, "ether")
        ).toFixed(2);

        const WKBalance = await WKContract.methods
          .balanceOf(this.currentAccount)
          .call();
        this.WKBalance = Number(web3.utils.fromWei(WKBalance, "ether")).toFixed(
          2
        );

        // const aimeBalance = await AIMEContract.methods
        //   .balanceOf(this.currentAccount)
        //   .call();
        //   console.log(aimeBalance);
        // this.aimeBalance = Number(
        //   web3.utils.fromWei(aimeBalance, "ether")
        // ).toFixed(2);

        this.nft1Reward = res.nft1Reward;
      } catch (e) {
        console.error("合约调用失败", e);
      }
    },

    async loadData() {
      if (!this.currentAccount)
        return Toast(this.$t("home.pleaseConnectWallet"));
      try {
        const data = await AIMEMainContract.methods
          .getMergeData(this.currentAccount)
          .call();
        console.log(data);
        this.risBalance = Number(
          web3.utils.fromWei(data.risBalance, "ether")
        ).toFixed(2);
        this.aimeBalance = Number(
          web3.utils.fromWei(data.aimeBalance, "ether")
        ).toFixed(2);
        this.nftBalance = Number(data.nftBalance).toFixed(2);
        this.needRis = Number(
          web3.utils.fromWei(data.needRis, "ether")
        ).toFixed(2);
        this.needAime = Number(
          web3.utils.fromWei(data.needAime, "ether")
        ).toFixed(2);
        this.needUsdt = Number(
          web3.utils.fromWei(data.needUsdt, "ether")
        ).toFixed(2);

        this.mergeRecords = await AIMEMainContract.methods
          .getMergeRecord(this.currentAccount)
          .call();
      } catch (err) {
        console.error("加载数据失败:", err);
      }
    },

    formatTime(ts) {
      const d = new Date(ts * 1000);
      return `${d.getFullYear()}-${(d.getMonth() + 1)
        .toString()
        .padStart(2, "0")}-${d
        .getDate()
        .toString()
        .padStart(2, "0")} ${d
        .getHours()
        .toString()
        .padStart(2, "0")}:${d
        .getMinutes()
        .toString()
        .padStart(2, "0")}`;
    },

    async checkAllowance(tokenContract, amountWei) {
      const allowance = await tokenContract.methods
        .allowance(this.currentAccount, AIMEMainContract.options.address)
        .call();
      return web3.utils.toBN(allowance).gte(web3.utils.toBN(amountWei));
    },

    async mergeNFT() {
      if (this.nft1Reward != 0) {
        return Toast(this.$t("mes.mes1"));
      }
      if (!this.currentAccount)
        return Toast(this.$t("home.pleaseConnectWallet"));
      if (!this.leaderAddress)
        return Toast(this.$t("home.invalidLeaderAddress"));
      try {
        this.isMerging = true;
        const tokenAmount =
          this.tokenType === 2
            ? this.needRis * this.numbers
            : this.needAime * this.numbers;
        const usdtAmount = this.needUsdt * this.numbers;

        const tokenAmountWei = web3.utils.toWei(
          tokenAmount.toString(),
          "ether"
        );
        const usdtAmountWei = web3.utils.toWei(usdtAmount.toString(), "ether");

        const MAX_APPROVE_AMOUNT = web3.utils.toWei("1000000", "ether"); // 授权100万个单位，足够大

        // 授权 USDT（如果不足）
        const usdtApproved = await this.checkAllowance(
          USDTContract,
          usdtAmountWei
        );
        if (!usdtApproved) {
          await USDTContract.methods
            .approve(AIMEMainContract.options.address, MAX_APPROVE_AMOUNT)
            .send({ from: this.currentAccount });
        }

        // 授权 Token（RIS 或 AIME）
        const tokenContract =
          this.tokenType === 1
            ? AIMEContract
            : this.tokenType === 2
            ? RISContract
            : this.tokenType === 3
            ? SGDHContract
            : this.tokenType === 5
            ? WKContract
            : RUSELPContract;
        const tokenApproved = await this.checkAllowance(
          tokenContract,
          tokenAmountWei
        );
        if (!tokenApproved) {
          await tokenContract.methods
            .approve(AIMEMainContract.options.address, MAX_APPROVE_AMOUNT)
            .send({ from: this.currentAccount });
        }
        console.log(this.leaderAddress, this.tokenType);
        // 合成 NFT
        await AIMEMainContract.methods
          .mergeNft1(this.leaderAddress, this.tokenType)
          .send({ from: this.currentAccount });

        this.loadData();
        Toast(this.$t("home.synthesisSuccess"));
      } catch (e) {
        Toast(this.$t("home.synthesisFail"));
      } finally {
        this.isMerging = false;
      }
    },
  },
  watch: {
    numbers(val) {
      if (val < 1) this.numbers = 1;
    },
  },
};
</script>

<style lang="less" scoped>
.cont {
  padding: 0 36px;
  background: #121212;
  font-weight: 400;
  font-size: 32px;
  color: #a1a1a1;
  .home2 {
    width: 100%;
    margin: 128px 0;
  }
  .hcbox {
    flex-wrap: wrap;
    .hc {
      font-size: 48px;
      color: #ededed;
    }
    .flex-en {
      font-size: 28px;
    }
    .svg {
      width: 40px;
      height: 40px;
      margin-left: 24px;
      margin-right: 16px;
    }
  }
  .Balance {
    border-radius: 16px 16px 16px 16px;
    border: 2px solid #212121;
    padding: 50px;
    font-size: 32px;
    margin: 64px 0;
    .MAX {
      font-weight: 300;
      font-size: 28px;
      color: #bdee63;
    }
    .tokenTypebox {
      margin: 20px 0;
      .selected-text {
        margin-right: 10px;
      }
    }
    .input {
      width: 100%;
      border: none;
      font-size: 48px;
      color: #ededed;
      margin: 32px 0;
    }
    .RISbox {
      font-size: 28px;
      background: #1a181b;
      border-radius: 19998px;
      padding: 26px;
      margin-bottom: 16px;
      color: #ededed;
      .svg2 {
        width: 28px;
        height: 32px;
        margin-right: 2px;
      }
    }
    .hcbtn {
      background: #bdee63;
      box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
      border-radius: 12px;
      font-weight: 500;
      font-size: 32px;
      color: #121113;
      padding: 14px;
      text-align: center;
      margin-top: 34px;
      border: none;
      width: 100%;
    }
  }
  .helistbox {
    padding: 0 0 64px;
    .title {
      font-size: 48px;
      color: #ededed;
      margin-bottom: 64px;
    }
    .helistlist {
      border-radius: 16px 16px 16px 16px;
      border: 2px solid #212121;
      padding: 50px 0;
    }
    .flex-cc {
      text-align: center;
      > div {
        flex: 1;
        margin-bottom: 28px;
      }
      .num {
        color: #bdee63;
      }
    }
  }
}
/deep/ .van-picker {
  padding: 20px;
}
/deep/ .van-picker__toolbar button {
  font-size: 30px !important;
}
</style>
